package cn.gbase.jiangsu.data.transfer.service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang.StringUtils;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.Sqls;
import org.nutz.dao.impl.sql.SqlTemplate;
import org.nutz.dao.pager.Pager;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.util.cri.SqlExpressionGroup;
import org.nutz.ioc.aop.Aop;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.Mvcs;
import org.nutz.service.IdEntityService;
import org.nutz.trans.Atom;
import org.nutz.trans.Trans;

import cn.gbase.jiangsu.data.transfer.bean.Community;
import cn.gbase.jiangsu.data.transfer.bean.CommunityBuilding;
import cn.gbase.jiangsu.data.transfer.bean.Company;
import cn.gbase.jiangsu.data.transfer.bean.CompanyToBuilding;
import cn.gbase.jiangsu.data.transfer.bean.ForumTopic;
import cn.gbase.jiangsu.data.transfer.bean.OrderSupplierView;
import cn.gbase.jiangsu.data.transfer.bean.Product;
import cn.gbase.jiangsu.data.transfer.bean.ProductComment;
import cn.gbase.jiangsu.data.transfer.bean.ProductOrder;
import cn.gbase.jiangsu.data.transfer.bean.ProductOrderDetail;
import cn.gbase.jiangsu.data.transfer.bean.RefundDetail;
import cn.gbase.jiangsu.data.transfer.bean.RefundLog;
import cn.gbase.jiangsu.data.transfer.bean.ShopUser;
import cn.gbase.jiangsu.data.transfer.bean.ShopUserView;
import cn.gbase.jiangsu.data.transfer.bean.ShopUsersGlasses;
import cn.gbase.jiangsu.data.transfer.bean.ShopUsersPointLog;
import cn.gbase.jiangsu.data.transfer.bean.ShopUsersTrade;
import cn.gbase.jiangsu.data.transfer.bean.Supplier;
import cn.gbase.jiangsu.data.transfer.bean.SupplierInfo;
import cn.gbase.jiangsu.data.transfer.bean.SupplierToCommunity;
import cn.gbase.jiangsu.data.transfer.bean.SupplierUser;
import cn.gbase.jiangsu.data.transfer.bean.SystemUser;
import cn.gbase.jiangsu.data.transfer.common.Constants;
import cn.gbase.jiangsu.data.transfer.util.CommonUtil;
import cn.gbase.jiangsu.data.transfer.util.DefaultPasswordEncoder;
import cn.gbase.jiangsu.data.transfer.util.SMSUtil;
import cn.gbase.jiangsu.data.transfer.vo.ReadyProductVO;

import com.google.common.collect.Maps;

@IocBean(args = { "refer:dao" })
public class SupplierService extends IdEntityService<Supplier> {

	@Inject
	private ProductSortTreeNodeService productSortTreeNodeService;

	@Inject
	private SystemService systemService;

	public SupplierService() {
		super();
	}

	private final SimpleDateFormat sfd = new SimpleDateFormat("yyyy年MM月dd日");

	public SupplierService(Dao dao) {
		super(dao);
	}

	/**
	 * 根据ID取得供应商.
	 * 
	 * @param SupplierId
	 * @return
	 */
	public Supplier getSupplier(int SupplierId) {
		return this.dao().fetch(Supplier.class, SupplierId);
	}

	/**
	 * 更新商品信息.
	 * 
	 * @param product
	 */
	public Object updateOrSaveInfo(SupplierInfo info, SupplierUser u, String idNew) {
		SupplierInfo si = this.dao().fetch(SupplierInfo.class, info.getId());
		if (si == null) {
			si = (SupplierInfo) saveInfo(info, u, idNew);
		} else {
			si.setSupplierInfo(info.getSupplierInfo());
			si.setSupplierPic1(info.getSupplierPic1());
			si.setSupplierPic2(info.getSupplierPic2());
			si.setSupplierPic3(info.getSupplierPic3());
			si.setSupplierPic4(info.getSupplierPic4());
			si.setSupplierPic5(info.getSupplierPic5());
			this.dao().update(si);
		}
		return si;
	}

	public Object saveInfo(SupplierInfo info, SupplierUser u, String idNew) {

		SupplierInfo si = new SupplierInfo();
		si.setSupplierId(u.getSupplierId());
		si.setSupplierInfo(info.getSupplierInfo());
		si.setSupplierPic1(info.getSupplierPic1());
		si.setSupplierPic2(info.getSupplierPic2());
		si.setSupplierPic3(info.getSupplierPic3());
		si.setSupplierPic4(info.getSupplierPic4());
		si.setSupplierPic5(info.getSupplierPic5());
		this.dao().insert(si);

		Sql sql = Sqls.create("update t_file set ywid = @ywid where ywid = @idNew");
		sql.params().set("ywid", si.getId());
		sql.params().set("idNew", idNew);
		this.dao().execute(sql);

		return si;
	}

	/**
	 * 取得供应商列表.
	 * 
	 * @param pageNumber
	 * @param name
	 * @return
	 */
	public QueryResult getSupplierList(int pageNumber, String keyword, String contact) {

		if (pageNumber <= 0) {
			pageNumber = 1;
		}

		// 拼接条件
		SqlExpressionGroup group = Cnd.exps("1", "=", 1);
		if (keyword != null && keyword.length() > 0) {
			group = group.and("supplierName", "like", "%" + keyword + "%");
		}
		if (contact != null && contact.length() > 0) {
			group = group.and("contact", "like", "%" + contact + "%");
		}
		group = group.and("deleteFlag", "<>", 1); //不是被删除的
		// 最大页数
		Pager pager = this.dao().createPager(pageNumber, Constants.LIST_ONE_PAGE_SIZE);

		// 查询记录总数
		int recordCount = this.dao().count(Supplier.class, Cnd.where(group));
		pager.setRecordCount(recordCount);

		// 没数据，直接返回
		if (recordCount == 0) {
			return new QueryResult(new ArrayList<Supplier>(0), pager);
		}

		// 计算页数
		int maxPageNumber = 0;
		if (recordCount % Constants.LIST_ONE_PAGE_SIZE == 0) {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE;
		} else {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE + 1;
		}
		if (pageNumber > maxPageNumber) {
			pager.setPageNumber(maxPageNumber);
		}

		// 查询
		List<Supplier> resultList = this.dao().query(Supplier.class, Cnd.where(group).desc("id"), pager); // 当前页面显示记录

		// 返回
		return new QueryResult(resultList, pager);
	}

	/**
	 * 取得供应商列表.
	 * 
	 * @return
	 */
	public List<Supplier> getSupplierList() {
		return this.dao().query(Supplier.class, Cnd.where("deleteFlag", "<>", 1));
	}

	public List<SupplierToCommunity> getSupplierToCom(Integer cid) {
		SqlExpressionGroup exp1 = Cnd.exps("communityId", "=", cid);
		Cnd and = Cnd.where(exp1);
		return this.dao().query(SupplierToCommunity.class, and);
	}

	public List<SupplierToCommunity> getSupplierToCommu(Integer supplierId) {
		// 拼接条件
		SqlExpressionGroup group = Cnd.exps("supplierId", "=", supplierId);
		List<SupplierToCommunity> resultList = this.dao().query(SupplierToCommunity.class, Cnd.where(group), null);
		return resultList;
	}

	public QueryResult getProductOrderList(String productId, String orderCode, String keyword, String nodeId,
			String status, Integer supplierId, String startTime, String endTime, String community) {
		String sql = "select * from order_supplier_view v where supplier_id=@supplierId";

		//商品id
		if (productId != null && productId.length() > 0)
			sql += " and product_id = @productId";
		else
			sql += " and 1=2";

		sql += " and status<>" + Constants.ORDER_STATUS_UNPAID + " and status<>" + Constants.ORDER_STATUS_CANCEL
				+ " and show_flag=" + Constants.ORDER_STATUS_PAID;

		// 订单编号
		if (orderCode != null && orderCode.length() > 0) {
			sql += " and code = @orderCode";
		}
		//商品名称
		if (keyword != null && keyword.length() > 0) {
			sql += " and product_name like @keyword";
		}
		// 订单状态
		if (status != null && status.length() > 0) {
			sql += " and status = @status";
		}
		// 负责小区
		if (community != null && community.length() > 0) {
			sql += " and community_id = @community";
		}
		// 下单时间
		if (startTime != null && startTime.length() > 0) {
			sql += " and create_time > @startTime";
		}

		// 下单时间
		if (endTime != null && endTime.length() > 0) {
			sql += " and create_time < @endTime";
		}
		Sql sqlTemp = Sqls.queryEntity(sql);
		sqlTemp.params().set("supplierId", supplierId);
		//商品id
		if (productId != null && productId.length() > 0)
			sqlTemp.params().set("productId", productId);
		if (orderCode != null && orderCode.length() > 0) {
			sqlTemp.params().set("orderCode", orderCode);
		}
		if (keyword != null && keyword.length() > 0) {
			sqlTemp.params().set("keyword", "%" + keyword + "%");
		}
		if (status != null && status.length() > 0) {
			sqlTemp.params().set("status", Integer.valueOf(status));
		}
		if (community != null && community.length() > 0) {
			sqlTemp.params().set("community", Integer.valueOf(community));
		}
		if (startTime != null && startTime.length() > 0) {
			sqlTemp.params().set("startTime", startTime + " 00:00:00");
		}
		if (endTime != null && endTime.length() > 0) {
			sqlTemp.params().set("endTime", endTime + " 23:59:59");
		}
		sqlTemp.setEntity(this.dao().getEntity(OrderSupplierView.class));
		this.dao().execute(sqlTemp);
		List<OrderSupplierView> list = sqlTemp.getList(OrderSupplierView.class);
		return new QueryResult(list, null);
	}

	/**
	 * 取得属于供货商的订单列表
	 * 
	 * @param currentPage
	 * @return 订单列表
	 */
	public QueryResult getSupplierOrderList(int pageNumber, String orderCode, String keyword, String nodeId,
			String status, Integer supplierId, String startTime, String endTime, String community) {

		// 每页显示记录数
		int iPageSize = 15;

		// 最大页数
		Pager pager = this.dao().createPager(pageNumber, iPageSize);

		String sql = "select sum(product_count) as sumcount,v.* from order_supplier_view v where supplier_id=@supplierId";

		// 拼接条件
		SqlExpressionGroup group2 = Cnd.exps("1", "=", 1);
		group2 = group2.and("supplierId", "=", supplierId);

		StringBuilder ids = new StringBuilder("");
		// 所属分类
		if (nodeId != null && nodeId.length() > 0) {
			int selectNodeId = Integer.valueOf(nodeId);
			String idStr = productSortTreeNodeService.getDescendantNodeIdStr(selectNodeId);
			group2 = group2.and("productSort", "in", idStr);

			List<Product> resultList = this.dao().query(Product.class, Cnd.where(group2).desc("id"), null);
			for (Product product : resultList)
				ids.append(product.getId() + ",");
			//商品id
			if (!"".equals(ids))
				sql += " and product_id in (" + ids.substring(0, ids.length() - 1) + ")";
			else
				sql += " and 1=2";
		}
		sql += " and status<>" + Constants.ORDER_STATUS_UNPAID + " and status<>" + Constants.ORDER_STATUS_CANCEL
				+ " and show_flag=" + Constants.ORDER_STATUS_PAID;

		// 订单编号
		if (orderCode != null && orderCode.length() > 0) {
			sql += " and code = @orderCode";
		}
		//商品名称
		if (keyword != null && keyword.length() > 0) {
			sql += " and product_name like @keyword";
		}
		// 订单状态
		if (status != null && status.length() > 0) {
			sql += " and status = @status";
		}
		// 负责小区
		if (community != null && community.length() > 0) {
			sql += " and community_id = @community";
		}
		// 下单时间
		if (startTime != null && startTime.length() > 0) {
			sql += " and create_time > @startTime";
		}

		// 下单时间
		if (endTime != null && endTime.length() > 0) {
			sql += " and create_time < @endTime";
		}
		sql += " GROUP BY product_id";
		Sql sqlTemp = Sqls.queryEntity(sql);
		sqlTemp.params().set("supplierId", supplierId);

		if (orderCode != null && orderCode.length() > 0) {
			sqlTemp.params().set("orderCode", orderCode);
		}
		if (keyword != null && keyword.length() > 0) {
			sqlTemp.params().set("keyword", "%" + keyword + "%");
		}
		if (status != null && status.length() > 0) {
			sqlTemp.params().set("status", Integer.valueOf(status));
		}
		if (community != null && community.length() > 0) {
			sqlTemp.params().set("community", Integer.valueOf(community));
		}
		if (startTime != null && startTime.length() > 0) {
			sqlTemp.params().set("startTime", startTime + " 00:00:00");
		}
		if (endTime != null && endTime.length() > 0) {
			sqlTemp.params().set("endTime", endTime + " 23:59:59");
		}
		sqlTemp.setEntity(this.dao().getEntity(OrderSupplierView.class));
		this.dao().execute(sqlTemp);
		List<OrderSupplierView> list = sqlTemp.getList(OrderSupplierView.class);
		sqlTemp.setPager(pager);
		this.dao().execute(sqlTemp);
		List<OrderSupplierView> listPage = sqlTemp.getList(OrderSupplierView.class);

		// 查询记录总数
		int recordCount = list.size();
		pager.setRecordCount(recordCount);

		// 没数据，直接返回
		if (recordCount == 0) {
			return new QueryResult(new ArrayList<OrderSupplierView>(0), pager);
		}

		// 计算页数
		int maxPageNumber = 0;
		if (recordCount % Constants.LIST_ONE_PAGE_SIZE == 0) {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE;
		} else {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE + 1;
		}
		if (pageNumber > maxPageNumber) {
			pager.setPageNumber(maxPageNumber);
		}

		String remoteAddr = "";
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/my.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
		}
		remoteAddr = properties.getProperty("serverIP");
		String picUpload = properties.getProperty("picUpload");
		for (OrderSupplierView osv : listPage)
			osv.setProductPic("http://" + remoteAddr + "/" + picUpload + osv.getProductPic());
		// 返回
		return new QueryResult(listPage, pager);
	}

	/**
	 * 取得属于供货商的订单列表
	 * 
	 * @param currentPage
	 * @return 订单列表
	 */
	public QueryResult getOrderDetailList(int pageNumber, String orderCode, String keyword, String nodeId,
			String status, Integer supplierId, String startTime, String endTime) {

		// 每页显示记录数
		int iPageSize = 15;

		// 最大页数
		Pager pager = this.dao().createPager(pageNumber, iPageSize);

		// 拼接条件
		SqlExpressionGroup group = Cnd.exps("supplierId", "=", supplierId);
		// 拼接条件
		SqlExpressionGroup group2 = Cnd.exps("1", "=", 1);
		group2 = group2.and("supplierId", "=", supplierId);

		// 所属分类
		if (nodeId != null && nodeId.length() > 0) {
			int selectNodeId = Integer.valueOf(nodeId);
			String idStr = productSortTreeNodeService.getDescendantNodeIdStr(selectNodeId);
			group2 = group2.and("productSort", "in", idStr);

			List<Product> resultList = this.dao().query(Product.class, Cnd.where(group2).desc("id"), null);
			List<Integer> pids = new ArrayList<Integer>();
			for (Product product : resultList)
				pids.add(product.getId());

			//商品id
			if (pids != null && pids.size() > 0)
				group = group.and("productId", "in", pids);
			else
				group = group.and("1", "=", 2);
		}
		group = group.and("status", "<>", Constants.ORDER_STATUS_UNPAID);
		group = group.and("status", "<>", Constants.ORDER_STATUS_CANCEL);
		group = group.and("showFlag", "=", Constants.ORDER_STATUS_PAID);
		// 订单编号
		if (orderCode != null && orderCode.length() > 0) {
			group = group.and("code", "=", orderCode);
		}
		//商品名称
		if (keyword != null && keyword.length() > 0) {
			group = group.and("productName", "like", "%" + keyword + "%");
		}
		// 订单状态
		if (status != null && status.length() > 0) {
			group = group.and("status", "=", Integer.valueOf(status));
		}
		// 下单时间
		if (startTime != null && startTime.length() > 0) {
			group = group.and("createTime", ">", startTime + " 00:00:00");
		}

		// 下单时间
		if (endTime != null && endTime.length() > 0) {
			group = group.and("createTime", "<", endTime + " 23:59:59");
		}
		// 查询记录总数
		int recordCount = this.dao().count(OrderSupplierView.class, Cnd.where(group).asc("productId"));
		pager.setRecordCount(recordCount);

		// 没数据，直接返回
		if (recordCount == 0) {
			return new QueryResult(new ArrayList<OrderSupplierView>(0), pager);
		}

		// 计算页数
		int maxPageNumber = 0;
		if (recordCount % Constants.LIST_ONE_PAGE_SIZE == 0) {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE;
		} else {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE + 1;
		}
		if (pageNumber > maxPageNumber) {
			pager.setPageNumber(maxPageNumber);
		}

		// 查询列表
		List<OrderSupplierView> orderList = this.dao().query(OrderSupplierView.class,
				Cnd.where(group).desc("createTime"), pager);
		String remoteAddr = "";
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/my.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
		}
		remoteAddr = properties.getProperty("serverIP");
		String picUpload = properties.getProperty("picUpload");
		for (OrderSupplierView osv : orderList)
			osv.setProductPic("http://" + remoteAddr + "/" + picUpload + osv.getProductPic());
		// 返回
		return new QueryResult(orderList, pager);
	}

	/**
	 * 取得属于供货商的订单列表
	 * 
	 * @param currentPage
	 * @return 订单列表
	 */
	public QueryResult getOrderList(int pageNumber, String status, Integer supplierId, String startTime,
			String endTime, String community, String address, String orderCode, int orderType) {

		// 每页显示记录数
		int iPageSize = 15;

		// 最大页数
		Pager pager = this.dao().createPager(pageNumber, iPageSize);

		// 拼接条件
		SqlExpressionGroup group = Cnd.exps("supplierId", "=", supplierId);
		// 拼接条件
		group = group.and("showFlag", "=", Constants.ORDER_STATUS_PAID);
		group = group.and("orderType", "=", orderType);
		group = group.and("status", "<>", Constants.ORDER_STATUS_UNPAID);
		group = group.and("status", "<>", Constants.ORDER_STATUS_CANCEL);
		//		group = group.and("status", "<>", Constants.ORDER_STATUS_DONE);
		//		group = group.and("status", "<>", Constants.ORDER_ARRIVE_STATION);
		//		group = group.and("status", "<>", Constants.ORDER_STATUS_SHIPPED);
		if (community != null && community.length() > 0) {
			SqlExpressionGroup group2 = Cnd.exps("1", "=", 1);
			group2 = group2.and("communityId", "=", Integer.valueOf(community));

			List<ShopUserView> resultList = this.dao().query(ShopUserView.class, Cnd.where(group2).desc("id"), null);
			List<Integer> pids = new ArrayList<Integer>();
			for (ShopUserView product : resultList)
				pids.add(product.getId());

			//用户id
			if (pids != null && pids.size() > 0)
				group = group.and("userId", "in", pids);
			else
				group = group.and("1", "=", 2);
		}
		// 订单状态
		if (status != null && status.length() > 0) {
			group = group.and("status", "=", Integer.valueOf(status));
		}
		// 订单号
		if (StringUtils.isNotBlank(orderCode)) {
			group = group.and("orderCode", "like", "%" + orderCode + "%");
		}
		// 收货地址
		if (StringUtils.isNotBlank(address)) {
			group = group.and("address", "like", "%" + address + "%");
		}
		// 下单时间
		if (startTime != null && startTime.length() > 0) {
			group = group.and("createTime", ">", startTime + " 00:00:00");
		}

		// 下单时间
		if (endTime != null && endTime.length() > 0) {
			group = group.and("createTime", "<", endTime + " 23:59:59");
		}

		// 查询记录总数
		int recordCount = this.dao().count(ProductOrder.class, Cnd.where(group).asc("createTime"));
		pager.setRecordCount(recordCount);

		// 没数据，直接返回
		if (recordCount == 0) {
			return new QueryResult(new ArrayList<ProductOrder>(0), pager);
		}

		// 计算页数
		int maxPageNumber = 0;
		if (recordCount % Constants.LIST_ONE_PAGE_SIZE == 0) {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE;
		} else {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE + 1;
		}
		if (pageNumber > maxPageNumber) {
			pager.setPageNumber(maxPageNumber);
		}

		// 查询列表
		List<ProductOrder> orderList = this.dao().query(ProductOrder.class, Cnd.where(group).asc("createTime"), pager);

		//找非实物订单
		String sql = "select DISTINCT(fodv.order_id) from product pro inner join goodes_order_detail_view fodv on fodv.product_id=pro.id where virtual_flag="
				+ Constants.VIRTUAL_FLAG;
		SqlTemplate sqlTemplate = new SqlTemplate(this.dao());
		List<Integer> list = sqlTemplate.queryForList(sql, null, null, Integer.class);

		for (ProductOrder order : orderList) {
			order.setServiceRemark(getCompanyName(order.getUserId()));
			order.setVirtualFlag(0);
			for (Integer id : list) {
				if (id.intValue() == order.getId()) {
					order.setVirtualFlag(1);
					break;
				}
			}
		}
		// 返回
		return new QueryResult(orderList, pager);
	}

	/**
	 * 取得属于供货商的订单列表
	 * 
	 * @param currentPage
	 * @return 订单列表
	 */
	public QueryResult getOldOrderList(int pageNumber, String status, Integer supplierId, String startTime,
			String endTime, String community, String orderCode, String address) {

		// 每页显示记录数
		int iPageSize = 15;

		// 最大页数
		Pager pager = this.dao().createPager(pageNumber, iPageSize);

		// 拼接条件
		SqlExpressionGroup group = Cnd.exps("supplierId", "=", supplierId);
		// 拼接条件
		group = group.and("showFlag", "=", Constants.ORDER_STATUS_PAID);
		group = group.and("status", "<>", Constants.ORDER_STATUS_UNPAID);
		group = group.and("status", "<>", Constants.ORDER_STATUS_CANCEL);
		//				group = group.and("status", "<>", Constants.ORDER_DISPATCH_STATION);
		group = group.and("status", "<>", Constants.ORDER_STATUS_PAID);
		if (community != null && community.length() > 0) {
			SqlExpressionGroup group2 = Cnd.exps("1", "=", 1);
			group2 = group2.and("communityId", "=", Integer.valueOf(community));

			List<ShopUserView> resultList = this.dao().query(ShopUserView.class, Cnd.where(group2).desc("id"), null);
			List<Integer> pids = new ArrayList<Integer>();
			for (ShopUserView product : resultList)
				pids.add(product.getId());

			//用户id
			if (pids != null && pids.size() > 0)
				group = group.and("userId", "in", pids);
			else
				group = group.and("1", "=", 2);
		}
		// 订单状态
		if (status != null && status.length() > 0) {
			group = group.and("status", "=", Integer.valueOf(status));
		}
		// 订单号
		if (StringUtils.isNotBlank(orderCode)) {
			group = group.and("orderCode", "like", "%" + orderCode + "%");
		}
		// 收货地址
		if (StringUtils.isNotBlank(address)) {
			group = group.and("address", "like", "%" + address + "%");
		}
		// 下单时间
		if (startTime != null && startTime.length() > 0) {
			group = group.and("createTime", ">", startTime + " 00:00:00");
		}

		// 下单时间
		if (endTime != null && endTime.length() > 0) {
			group = group.and("createTime", "<", endTime + " 23:59:59");
		}

		// 查询记录总数
		int recordCount = this.dao().count(ProductOrder.class, Cnd.where(group).desc("createTime"));
		pager.setRecordCount(recordCount);

		// 没数据，直接返回
		if (recordCount == 0) {
			return new QueryResult(new ArrayList<ProductOrder>(0), pager);
		}

		// 计算页数
		int maxPageNumber = 0;
		if (recordCount % Constants.LIST_ONE_PAGE_SIZE == 0) {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE;
		} else {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE + 1;
		}
		if (pageNumber > maxPageNumber) {
			pager.setPageNumber(maxPageNumber);
		}

		// 查询列表
		List<ProductOrder> orderList = this.dao().query(ProductOrder.class, Cnd.where(group).desc("createTime"), pager);
		for (ProductOrder order : orderList)
			order.setServiceRemark(getCompanyName(order.getUserId()));
		// 返回
		return new QueryResult(orderList, pager);
	}

	public String getCompanyName(int uid) {
		ShopUserView suv = this.dao().fetch(ShopUserView.class, Cnd.where("id", "=", uid));
		return suv == null ? "" : suv.getCommunityName();
	}

	public void sendOrder(int id) {
		ProductOrder productOrder = this.dao().fetch(ProductOrder.class, id);
		/*//根据供应商ID查出供应商
		Supplier supplier = this.dao().fetch(Supplier.class, supplierId);
		//看是不是非实物订单
		String sqlStr = "select DISTINCT(fodv.order_id) from product pro inner join goodes_order_detail_view fodv on fodv.product_id=pro.id where virtual_flag="
				+ Constants.VIRTUAL_FLAG + " and order_id = @orderId";
		Sql sql = Sqls.create(sqlStr);
		sql.params().set("orderId", id);
		sql.setCallback(Sqls.callback.str());
		this.dao().execute(sql);
		String orderId = sql.getObject(String.class);*/
		//如果已配货
		if (productOrder.getStatus() == Constants.ORDER_DISPATCH_STATION) {
			this.dao().update(ProductOrder.class, Chain.make("status", 2), Cnd.where("id", "=", id));
			//如果为线下供应商，直接把状态改成已完成
			/*if (1 == supplier.getOfflineFlag()) {
				this.dao().update(ProductOrder.class, Chain.make("status", 3), Cnd.where("id", "=", id));
			}*/
			//判断是否为非实物订单
			/*if (orderId != null) {
				this.dao().update(ProductOrder.class, Chain.make("status", 3), Cnd.where("id", "=", id));
			}*/
		}

	}

	public void finishOrder(int id) {
		ProductOrder productOrder = this.dao().fetch(ProductOrder.class, id);
		//如果已付款
		if (productOrder.getStatus() == Constants.ORDER_STATUS_PAID)
			this.dao().update(ProductOrder.class, Chain.make("status", 3), Cnd.where("id", "=", id));
	}

	public void dependOrder(int id) {
		ProductOrder productOrder = this.dao().fetch(ProductOrder.class, id);
		//如果已付款
		if (productOrder.getStatus() == Constants.ORDER_STATUS_PAID)
			this.dao().update(ProductOrder.class, Chain.make("status", 6), Cnd.where("id", "=", id));
	}

	public void getOrder(int id) {
		ProductOrder productOrder = this.dao().fetch(ProductOrder.class, id);
		//如果已到达社区服务站
		if (productOrder.getStatus() == Constants.ORDER_ARRIVE_STATION) {
			productOrder.setStatus(Constants.ORDER_STATUS_DONE);
			productOrder.setActualDate(new Date());
			this.dao().update(productOrder);
			//会员
			int userId = productOrder.getUserId();
			//总价
			BigDecimal totalPrice = productOrder.getTotalPrice();
			ShopUser user = this.dao().fetch(ShopUser.class, userId);
			List<ShopUserView> userview = this.dao().query(ShopUserView.class, Cnd.where("id", "=", userId));
			ShopUserView shopUserView = userview.get(0);
			//每百元积分
			int pointPercent = shopUserView.getPointPercent();
			//积分
			BigDecimal scale = (totalPrice.multiply(new BigDecimal(pointPercent))).divide(new BigDecimal(100))
					.setScale(0, BigDecimal.ROUND_HALF_UP);
			//要加事务***********************
			if (0 < scale.intValue()) {
				List<Company> companyList = this.dao().query(Company.class,
						Cnd.where("communityId", "=", user.getCommunityId()));

				//设置积分
				user.setShopPoint(user.getShopPoint() + scale.intValue());
				ShopUsersPointLog log = new ShopUsersPointLog();
				log.setUserId(userId);
				log.setCreateTime(new Date());
				log.setPoint(scale.intValue());
				log.setDescription("您的订单" + productOrder.getOrderCode() + "完成确认收货，奖励积分：" + scale.intValue());
				this.dao().insert(log);
				this.dao().update(user);
				Date now = new Date();
				ForumTopic topic = new ForumTopic();
				topic.setForumId(Constants.FORUM_ID_U2C); // 服务站与用户之间的帖子
				topic.setFromType("C"); // 运营商发帖
				topic.setToType("U"); // 供货商收贴
				if (companyList != null && companyList.size() > 0) {
					Company company = companyList.get(0);
					topic.setFromId(company.getId()); // 服务站固定写0
				}
				topic.setToId(userId);
				topic.setTopicTitle("订单积分到账通知");
				topic.setTopicContent("您的订单" + productOrder.getOrderCode() + "完成确认收货，奖励积分：" + scale.intValue());
				topic.setAddTime(now); // 发表时间
				topic.setLastPostTime(now); // 最后回复时间
				topic.setReplyNumber(0); // 回复数0
				topic.setClick(0); // 点击数0
				topic.setIsTop("N"); // 不置顶
				// 添加主题
				this.dao().insert(topic);
			}
		}
	}

	public void serverOrder(int id) {
		ProductOrder productOrder = this.dao().fetch(ProductOrder.class, id);
		//如果已下单
		if (productOrder.getStatus() == Constants.ORDER_STATUS_UNPAID) {
			productOrder.setStatus(Constants.ORDER_STATUS_DONE);
			productOrder.setActualDate(new Date());
			this.dao().update(productOrder);
		}
	}

	public void serverOrderRemarkSave(int id, String serviceRemark) {
		ProductOrder productOrder = this.dao().fetch(ProductOrder.class, id);
		productOrder.setServiceRemark(serviceRemark);
		this.dao().update(productOrder);
		//如果已下单
		/*if (productOrder.getStatus() == Constants.ORDER_STATUS_UNPAID) {
			productOrder.setStatus(Constants.ORDER_STATUS_DONE);
			productOrder.setActualDate(new Date());
			productOrder.setServiceRemark(serviceRemark);
			this.dao().update(productOrder);
		}*/
	}

	public ProductOrder getGoodsOrder(int id) {
		ProductOrder order = this.dao().fetch(ProductOrder.class, Cnd.where("id", "=", id));
		return order;
	}

	public ProductComment getOrderComment(int id) {
		List<ProductComment> detailList = this.dao().query(ProductComment.class, Cnd.where("orderId", "=", id));
		if (detailList != null && detailList.size() > 0)
			return detailList.get(0);
		return null;
	}

	/**
	 * 取得订单中的商品列表，包含是否已评价.
	 * 
	 * @param orderId
	 *            订单ID
	 * @return
	 */
	public QueryResult getOrderProductList(int orderId) {

		// 检查订单
		int count = this.dao().count(ProductOrder.class, Cnd.where("id", "=", orderId));
		if (count == 0) {
			return new QueryResult(new ArrayList<ProductOrderDetail>(), this.dao().createPager(1, 1));
		}

		// 商品列表
		List<ProductOrderDetail> detailList = this.dao().query(ProductOrderDetail.class,
				Cnd.where("orderId", "=", orderId));

		// 取是否已评价
		//		if (detailList.size() > 0) {
		//			for (ProductOrderDetail detail : detailList) {
		//				int commentCount = this.dao().count(
		//						ProductComment.class,
		//						Cnd.where("orderId", "=", orderId)
		//								.and("productId", "=", detail.getProductId())
		//								.and("userId", "=", userId));
		//				detail.setCommentCount(commentCount);
		//			}
		//		}
		// 返回
		return new QueryResult(detailList, this.dao().createPager(1, 1));
	}

	public void turnOrder(int id) {
		ProductOrder productOrder = this.dao().fetch(ProductOrder.class, id);
		//如果已发货
		if (productOrder.getStatus() == Constants.ORDER_STATUS_SHIPPED) {
			ShopUser shopUser = this.dao().fetch(ShopUser.class, productOrder.getUserId());
			//手机
			String mobile = shopUser.getMobile();
			//会员名
			String username = shopUser.getUsername();
			Date createTime = productOrder.getCreateTime();
			sfd.format(createTime);
			this.dao().update(ProductOrder.class, Chain.make("status", 5), Cnd.where("id", "=", id));
			String template = systemService.getSmsArriveTemplate();

			String corp = systemService.getSmsUserName();// 账户名
			String pwd = systemService.getSmsPassWord();// 密码
			String content = template.replace("${用户名}", username).replace("${订单时间}", sfd.format(createTime))
					.replace("${订单号}", productOrder.getOrderCode());

			if (mobile != null && mobile.length() > 0)
				SMSUtil.sendSMS(mobile, content, "", corp, pwd, Constants.SMS_TYPE_ARRIVE_MSG, dao());

		}
	}

	public QueryResult getOrderDetail(String orderCode) {

		// 拼接条件
		SqlExpressionGroup group = Cnd.exps("1", "=", 1);

		// 订单编号
		if (orderCode != null && orderCode.length() > 0) {
			group = group.and("id", "=", orderCode);
		}

		// 查询列表
		List<ProductOrder> orderList = this.dao().query(ProductOrder.class, Cnd.where(group).desc("createTime"), null);
		String remoteAddr = "";
		Properties properties = new Properties();
		java.io.InputStream inputstream = getClass().getResourceAsStream("/my.properties");
		try {
			properties.load(inputstream);
		} catch (Exception ex) {
		}
		remoteAddr = properties.getProperty("serverIP");
		String picUpload = properties.getProperty("picUpload");
		// 取得订单商品列表
		for (ProductOrder order : orderList) {

			// 自定义查询
			String sqlStr = "select D.id,D.product_name,D.user_id,D.product_pic1,D.product_count,D.product_field_value,D.sell_price from order_supplier_view D where D.order_id= <orderId> ";
			sqlStr = sqlStr.replace("<orderId>", "" + order.getId());

			Sql sql = Sqls.create(sqlStr);
			sql.setCallback(Sqls.callback.entities());
			sql.setEntity(this.dao().getEntity(OrderSupplierView.class));
			this.dao().execute(sql);
			List<OrderSupplierView> resultList = sql.getList(OrderSupplierView.class);

			for (OrderSupplierView osv : resultList) {
				osv.setProductPic("http://" + remoteAddr + "/" + picUpload + osv.getProductPic());
				if (osv.getProductName().contains("眼镜")) {
					Integer userId = osv.getUserId();
					ShopUsersGlasses usersGlasses = dao().fetch(ShopUsersGlasses.class,
							Cnd.where("userId", "=", userId));
					osv.setSug(usersGlasses);
				}
			}
			order.setOsvList(resultList);
		}
		Pager pager = new Pager();
		// 返回
		return new QueryResult(orderList, pager);
	}

	public List<CompanyToBuilding> getCommunityToCom(Integer cid) {
		SqlExpressionGroup exp1 = Cnd.exps("companyId", "=", cid);
		Cnd and = Cnd.where(exp1);
		return this.dao().query(CompanyToBuilding.class, and);
	}

	public List<Integer> getSuppliers(Integer sid) {
		List<Integer> sids = new ArrayList<Integer>();

		List<CompanyToBuilding> communityToCom = getCommunityToCom(sid);
		for (CompanyToBuilding community : communityToCom) {
			CommunityBuilding building = this.dao().fetch(CommunityBuilding.class, community.getBuildingId());
			List<SupplierToCommunity> supplierToCom = getSupplierToCom(building.getCommunityId());
			for (SupplierToCommunity stc : supplierToCom) {
				sids.add(stc.getSupplierId());
			}
		}

		//		SqlExpressionGroup exp1 = Cnd.exps("id", "in", sids);
		//		Cnd and = Cnd.where(exp1);
		//		return this.dao().query(Supplier.class, and);
		return sids;
	}

	public List<Integer> getSuppliersByCommunity(Integer cid) {
		List<Integer> sids = new ArrayList<Integer>();
		List<SupplierToCommunity> supplierToCom = getSupplierToCom(cid);
		for (SupplierToCommunity stc : supplierToCom) {
			sids.add(stc.getSupplierId());
		}
		return sids;
	}

	/**
	 * 添加或更新供应商.
	 * 
	 * @param Supplier
	 * @return
	 */
	public boolean addOrUpdSupplier(Supplier Supplier) {
		if (Supplier.getId() > 0) {
			return updateSupplier(Supplier);
		}
		return addSupplier(Supplier);
	}

	/**
	 * 添加供应商.
	 * 
	 * @param Supplier
	 * @return
	 */
	public boolean addSupplier(Supplier Supplier) {

		// 添加供应商
		this.dao().insert(Supplier);
		return true;
	}

	/**
	 * 更新供应商.
	 * 
	 * @param Supplier
	 * @return
	 */
	public boolean updateSupplier(Supplier Supplier) {
		this.dao().update(Supplier);
		return true;
	}

	/**
	 * 删除供应商.
	 * 
	 * @param SupplierId
	 */
	public void deleteSupplier(int SupplierId) {
		Supplier Supplier = this.dao().fetch(Supplier.class, SupplierId); // 根据ID删除
		Supplier.setDeleteFlag(1);
		this.dao().update(Supplier);
		SqlExpressionGroup exp1 = Cnd.exps("supplierId", "=", SupplierId);
		Cnd and = Cnd.where(exp1);
		List<SupplierUser> list = this.dao().query(SupplierUser.class, and);
		for (SupplierUser su : list)
			deleteUser(su.getId());
		List<Product> resultList = this.dao().query(Product.class, and); // 当前页面显示记录
		for (Product pu : resultList) {
			pu.setDeleteFlag(1);
			this.dao().update(pu);
		}
		//供应商的用户，删除不？还是把供应商逻辑删除？
	}

	// -----------------------------下面是供应商的用户管理------------------------

	/**
	 * 根据ID取得用户.
	 * 
	 * @param userId
	 * @return
	 */
	public SupplierUser getUser(int userId) {
		return this.dao().fetch(SupplierUser.class, userId);
	}

	/**
	 * 取得用户列表.
	 * 
	 * @param pageNumber
	 * @param username
	 * @param realname
	 * @return
	 */
	public QueryResult getUserList(int pageNumber, String username, String realname, int sid) {

		if (pageNumber <= 0) {
			pageNumber = 1;
		}

		// 拼接条件
		SqlExpressionGroup group = Cnd.exps("1", "=", 1);
		if (username != null && username.length() > 0) {
			group = group.and("username", "like", "%" + username + "%");
		}
		if (realname != null && realname.length() > 0) {
			group = group.and("remark", "like", "%" + realname + "%");
		}
		group = group.and("supplierId", "=", sid); //供应商ID
		group = group.and("status", "<>", 0); //不是被删除的
		// 最大页数
		Pager pager = this.dao().createPager(pageNumber, Constants.LIST_ONE_PAGE_SIZE);

		// 查询记录总数
		int recordCount = this.dao().count(SupplierUser.class, Cnd.where(group));
		pager.setRecordCount(recordCount);

		// 没数据，直接返回
		if (recordCount == 0) {
			return new QueryResult(new ArrayList<SupplierUser>(0), pager);
		}

		// 计算页数
		int maxPageNumber = 0;
		if (recordCount % Constants.LIST_ONE_PAGE_SIZE == 0) {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE;
		} else {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE + 1;
		}
		if (pageNumber > maxPageNumber) {
			pager.setPageNumber(maxPageNumber);
		}

		// 查询
		List<SupplierUser> resultList = this.dao().query(SupplierUser.class, Cnd.where(group).desc("id"), pager); // 当前页面显示记录

		// 返回
		return new QueryResult(resultList, pager);

	}

	/**
	 * 添加或更新用户.
	 * 
	 * @param user
	 * @return
	 */
	@Aop("validationInterceptor")
	public boolean addOrUpdUser(SupplierUser user) {
		if (user.getId() > 0) {
			return updateUser(user);
		}
		return addUser(user);
	}

	/**
	 * 添加用户.
	 * 
	 * @param user
	 * @return
	 */
	public boolean addUser(SupplierUser user) {

		// 检查用户是否存在
		SupplierUser dbUser = this.dao().fetch(SupplierUser.class,
				Cnd.where("username", "=", user.getUsername()).and("status", "<>", 0));
		if (dbUser != null) {
			return false;
		}
		// 当前登录用户
		SystemUser loginUser = (SystemUser) Mvcs.getReq().getSession().getAttribute("user");
		if (loginUser != null)
			//设置字段信息
			user.setCreateUser(loginUser.getUsername());

		else {
			SupplierUser loginSupplier = (SupplierUser) Mvcs.getReq().getSession().getAttribute("supplierUser");
			user.setCreateUser(loginSupplier.getUsername());
		}
		user.setAddtime(new Date());
		user.setStatus(2);

		user.setPw(new DefaultPasswordEncoder("MD5").encode(user.getPw()));
		//插入DB
		this.dao().insert(user);
		return true;
	}

	/**
	 * 更新用户.
	 * 
	 * @param user
	 * @return
	 */
	public boolean updateUser(SupplierUser user) {
		// 检查是否存在
		SupplierUser dbUser = this.dao().fetch(SupplierUser.class,
				Cnd.where("username", "=", user.getUsername()).and("id", "<>", user.getId()).and("status", "<>", 0));
		if (dbUser != null) {
			return false;
		}

		dbUser = this.dao().fetch(SupplierUser.class, user.getId());

		//更新字段
		dbUser.setAclStr(user.getAclStr());
		dbUser.setRemark(user.getRemark());
		dbUser.setUsername(user.getUsername());

		dbUser.setPw(new DefaultPasswordEncoder("MD5").encode(user.getPw()));
		//更新DB
		this.dao().update(dbUser);
		return true;
	}

	/**
	 * 删除用户.
	 * 
	 * @param userId
	 */
	public void deleteUser(int userId) {
		SupplierUser user = this.dao().fetch(SupplierUser.class, userId);
		user.setStatus(0);
		this.dao().update(user);
	}

	public String getAgentUserName(Integer community, Integer buildNo, String unitNo, Integer roomNo, String realName,
			String password) {
		ShopUserView shopUserView = this.dao().fetch(
				ShopUserView.class,
				Cnd.where("community_id", "=", community).and("building_id", "=", buildNo).and("unit_id", "=", unitNo)
						.and("room_id", "=", roomNo).and("realName", "=", realName));

		// 密码错误
		String encodePass = CommonUtil.encodeUserPw(password);
		//String encodePass = new DefaultPasswordEncoder("MD5").encode(password);
		if (shopUserView.getPw().equals(encodePass)) {
			return "true";
		} else {
			return "false";
		}
	}

	public List<Community> getOrderCommunity(int supplierId, String startTime, String endTime, Integer status) {
		String sql = "select * from community c where exists(select v.id from order_supplier_view v where v.community_id=c.id and v.supplier_id=@supplierId and v.show_flag="
				+ Constants.ORDER_STATUS_PAID;
		Map<String, Object> param = Maps.newHashMap();
		param.put("supplierId", supplierId);
		// 下单时间
		if (startTime != null && startTime.length() > 0) {
			sql += " and v.create_time > @startTime and v.create_time<@endTime";
			param.put("startTime", startTime + " 00:00:00");
			param.put("endTime", endTime + " 23:59:59");
		}
		// 订单状态
		if (status != null) {
			sql += " and v.status = @status";
			param.put("status", status);
		}
		sql += ")";
		SqlTemplate sqlTemplate = new SqlTemplate(this.dao());
		List<Community> result = sqlTemplate.query(sql, param, dao().getEntity(Community.class));
		return result;
	}

	/**
	 * 配货只要实物订单
	 * @param supplierId
	 * @param startTime
	 * @param endTime
	 * @param status
	 * @param community
	 * @return
	 */
	public List<ReadyProductVO> getReadyOrderList(int supplierId, String startTime, String endTime, Integer status,
			String community) {
		String sql = "select * from order_supplier_view v where supplier_id=@supplierId and v.show_flag="
				+ Constants.ORDER_STATUS_PAID + " and v.virtual_flag=" + Constants.VIRTUAL_NO_FLAG;
		String sql2 = "select DISTINCT product_id from order_supplier_view v where supplier_id=@supplierId and v.show_flag="
				+ Constants.ORDER_STATUS_PAID + " and v.virtual_flag=" + Constants.VIRTUAL_NO_FLAG;
		Map<String, Object> param = Maps.newHashMap();
		param.put("supplierId", supplierId);
		// 下单时间
		if (startTime != null && startTime.length() > 0) {
			sql += " and v.create_time > @startTime and v.create_time<@endTime";
			sql2 += " and v.create_time > @startTime and v.create_time<@endTime";
			param.put("startTime", startTime + " 00:00:00");
			param.put("endTime", endTime + " 23:59:59");
		}
		if (!StringUtils.isBlank(community)) {
			sql += " and v.community_id = @community";
			sql2 += " and v.community_id = @community";
			param.put("community", community);
		}
		// 订单状态
		if (status != null) {
			sql += " and v.status = @status";
			sql2 += " and v.status = @status";
			param.put("status", status);
		}
		SqlTemplate sqlTemplate = new SqlTemplate(this.dao());
		List<OrderSupplierView> result = sqlTemplate.query(sql, param, dao().getEntity(OrderSupplierView.class));
		List<Integer> productList = sqlTemplate.queryForList(sql2, null, param, Integer.class);
		List<ReadyProductVO> list = new ArrayList<ReadyProductVO>();
		for (Integer product : productList) {
			ReadyProductVO rpv = new ReadyProductVO();
			rpv.setProductId(product);
			rpv.setCommunityId(Integer.valueOf(community));
			int totalCount = 0;
			for (OrderSupplierView osv : result) {
				if (product.intValue() == osv.getProductId().intValue()) {
					rpv.setProductName(osv.getProductFieldValue() == null ? osv.getProductName() : osv.getProductName()
							+ "-" + osv.getProductFieldValue());
					rpv.setStockNumber(osv.getStockNumber());
					totalCount += osv.getProductCount();
				}
			}
			rpv.setProductCount(totalCount);
			list.add(rpv);
		}
		return list;
	}

	public void checkRefund(Integer supplierId, String communityId, List<ReadyProductVO> list, String startTime,
			String endTime, Integer status) {
		String sql = "select sum(product_count) from order_supplier_view v where supplier_id=@supplierId and v.show_flag="
				+ Constants.ORDER_STATUS_PAID;
		String sql2 = "select * from order_supplier_view v where supplier_id=@supplierId and v.show_flag="
				+ Constants.ORDER_STATUS_PAID;
		Map<String, Object> param = Maps.newHashMap();
		param.put("supplierId", supplierId);
		// 下单时间
		if (startTime != null && startTime.length() > 0) {
			sql += " and v.create_time > @startTime and v.create_time<@endTime";
			sql2 += " and v.create_time > @startTime and v.create_time<@endTime";
			param.put("startTime", startTime + " 00:00:00");
			param.put("endTime", endTime + " 23:59:59");
		}
		if (!StringUtils.isBlank(communityId)) {
			sql += " and v.community_id = @community";
			sql2 += " and v.community_id = @community";
			param.put("community", communityId);
		}
		// 订单状态
		if (status != null) {
			sql += " and v.status = @status";
			sql2 += " and v.status = @status";
			param.put("status", status);
		}
		if (list != null && list.size() > 0) {
			SqlTemplate sqlTemplate = new SqlTemplate(this.dao());
			for (ReadyProductVO rpv : list) {
				String sql3 = " and v.product_id = @productId order by create_time asc";
				param.put("productId", rpv.getProductId());
				Integer total = sqlTemplate.queryForInt(sql + sql3, param);
				if (rpv.getProductCount().intValue() != total.intValue()) {
					List<OrderSupplierView> result = sqlTemplate.query(sql2 + sql3, param,
							dao().getEntity(OrderSupplierView.class));
					preRefund(result, rpv.getProductCount());
				}
			}
			//配货
			List<OrderSupplierView> result = sqlTemplate.query(sql2, param, dao().getEntity(OrderSupplierView.class));
			for (OrderSupplierView osv : result)
				this.dao().update(ProductOrder.class, Chain.make("status", 6), Cnd.where("id", "=", osv.getOrderId()));
		}
	}

	public void preRefund(List<OrderSupplierView> list, int sellCount) {
		for (OrderSupplierView osv : list) {
			if (sellCount >= osv.getProductCount()) {
				sellCount = sellCount - osv.getProductCount();
			} else {
				refundProduct(osv.getOrderId(), osv, sellCount);
				sellCount = 0;
			}

		}
	}

	/**
	 * 订单部分商品退款.
	 * 
	 * @param orderId
	 *            订单ID
	 * @return
	 */
	public void refundProduct(Integer orderId, final OrderSupplierView detail, int productCount) {

		// 订单
		final ProductOrder order = this.dao().fetch(ProductOrder.class, orderId);

		// 订单商品列表
		List<ProductOrderDetail> detailList = getOrderDetailList(orderId);

		// 计算总退款金额（忽视优惠券等情况，运费就不退了）
		BigDecimal total = BigDecimal.ZERO;
		//退的数量
		int totalCount2 = 0;
		//剩的数量
		int totalCount = 0;
		for (ProductOrderDetail orderDetail : detailList) {
			String key = "" + detail.getId();
			if (detail.getId().intValue() == orderDetail.getId()) {
				total = total.add(detail.getSellPrice().multiply(
						new BigDecimal(detail.getProductCount() - productCount)));
				totalCount2 = detail.getProductCount() - productCount;
				totalCount += productCount;
			} else
				totalCount += detail.getProductCount();
		}
		//整单都没了，退运费
		if (0 == totalCount) {
			total.add(order.getDeliveryPrice());
		}
		// 账户余额
		final BigDecimal totalFinal = total;
		final Integer totalRefund = totalCount2;
		final Integer totalAll = totalCount;
		Trans.exec(new Atom() {
			@Override
			public void run() {
				// 退款表
				RefundLog log = new RefundLog();
				log.setCode(CommonUtil.createOrderCode()); // 退款订单Code
				log.setCreateTime(new Date());
				log.setOrderId(order.getId()); // 原订单ID
				log.setRefundAmount(totalFinal); // 退款金额
				log.setRefundRemark("订单部分商品缺货退款。");
				SupplierService.this.dao().insert(log);

				// 创建记录
				RefundDetail row = new RefundDetail();
				row.setRefundId(log.getId()); // 退款表ID
				row.setProductId(detail.getProductId());
				row.setProductFieldValue(detail.getProductFieldValue());
				row.setProductCount(totalRefund.intValue()); // 退款的数量
				row.setSellPrice(detail.getSellPrice());
				row.setSupplierPrice(detail.getSupplierPrice());
				SupplierService.this.dao().insert(row);

				// 订单中所有商品都退了，把快递费也退了
				if (0 == totalAll.intValue()) {
					cancelOrder(order.getId());
				} else {
					// 如果买了3个，退了3个，那么该行直接原表删除，就好像当初没买一样
					// 如果买了3个，退了2个，那么更新原行的数量
					if (totalRefund.intValue() == detail.getProductCount().intValue()) {
						SupplierService.this.dao().delete(ProductOrderDetail.class, detail.getId());
					} else if (totalRefund.intValue() < detail.getProductCount().intValue()) {
						SupplierService.this.dao().update(ProductOrderDetail.class,
								Chain.makeSpecial("productCount", "-" + totalRefund.intValue()),
								Cnd.where("id", "=", detail.getId()));
					}

					// 原订单的商品金额、订单金额要减去退款的金额
					SupplierService.this.dao().update(
							ProductOrder.class,
							Chain.makeSpecial("productPrice", "-" + totalFinal.toString()).addSpecial("totalPrice",
									"-" + totalFinal.toString()), Cnd.where("id", "=", order.getId()));
				}

				ShopUser user = SupplierService.this.dao().fetch(ShopUser.class, order.getUserId());
				// 都退回到账户余额
				refundToUserAccount(totalFinal, user, order.getId());
				//发站内通知，发手机短信
				String productName = detail.getProductName();
				if (!StringUtils.isBlank(detail.getProductFieldValue()))
					productName = detail.getProductName() + "-" + detail.getProductFieldValue();
				ForumTopic topic = new ForumTopic();
				topic.setTopicTitle("系统退款通知");
				topic.setTopicContent("抱歉，您订的" + productName + "现在没有货，请稍后再订。您的货款已被退回到您的账户");
				addTopic(topic, order.getUserId());
			}
		});
	}

	/**
	 * 取消订单.
	 * 
	 * @param id
	 *            订单ID
	 * @return
	 */
	public Map<String, String> cancelOrder(int id) {

		// 更新状态字段
		this.dao().update(ProductOrder.class, Chain.make("status", Constants.ORDER_STATUS_CANCEL),
				Cnd.where("id", "=", id));

		// 返回消息
		Map<String, String> m = new HashMap<String, String>();
		m.put("result", "OK");
		return m;
	}

	/**
	 * 退款到用户账户.
	 * 
	 * @param refundAmount
	 *            退款金额
	 * @param userId
	 *            用户ID
	 * @param orderId
	 *            订单ID
	 */
	private void refundToUserAccount(BigDecimal refundAmount, ShopUser user, int orderId) {

		// 更新余额
		this.dao().update(ShopUser.class, Chain.makeSpecial("accountBalance", "+" + refundAmount),
				Cnd.where("id", "=", user.getId()));

		// 写交易记录
		ShopUsersTrade trade = new ShopUsersTrade();
		trade.setUserId(user.getId());
		trade.setSeqNumber(CommonUtil.getRandomNumString(16)); // 流水号
		trade.setOrderId(orderId); // 订单ID
		trade.setTradeType(Constants.TRADE_TYPE_ORDER_REFUND); // 交易类型：订单退款
		trade.setTradeMoney(refundAmount); // 交易金额
		trade.setBalanceMoney(user.getAccountBalance()); // 账户余额
		trade.setCreateTime(new Date()); // 交易时间
		trade.setStatus(1); // 成功？
		this.dao().insert(trade);

	}

	public void addTopic(ForumTopic topic, int userId) {

		Date now = new Date();
		topic.setForumId(Constants.FORUM_ID_O2U); // 运营商与用户之间的帖子
		topic.setFromType("O"); // 运营商发帖
		topic.setToType("U"); // 供货商收贴
		topic.setFromId(0); // 运营商固定写0
		topic.setToId(userId); // 用户ID
		topic.setAddTime(now); // 发表时间
		topic.setLastPostTime(now); // 最后回复时间
		topic.setReplyNumber(0); // 回复数0
		topic.setClick(0); // 点击数0
		topic.setIsTop("N"); // 不置顶

		// 添加主题
		this.dao().insert(topic);

	}

	/**
	 * 取得订单中的商品列表，包含是否已评价.
	 * 
	 * @param orderId
	 *            订单ID
	 * @return
	 */
	public List<ProductOrderDetail> getOrderDetailList(Integer orderId) {

		// 商品列表
		List<ProductOrderDetail> detailList = this.dao().query(ProductOrderDetail.class,
				Cnd.where("orderId", "=", orderId));

		// 取是否已评价
		if (detailList.size() > 0) {
			for (ProductOrderDetail detail : detailList) {
				int commentCount = this.dao().count(ProductComment.class,
						Cnd.where("orderId", "=", orderId).and("productId", "=", detail.getProductId()));
				detail.setCommentCount(commentCount);
			}
		}

		// 返回
		return detailList;
	}
}
